package com.xqboss.common.core.domain;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xqboss.common.constant.HttpStatus;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

/**
 * 封装mybatis分页返回数据
 *
 * @author lujiahong
 * @date 2024-01-15
 */
@Data
@NoArgsConstructor
public class PageResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /** 成功 */
    private static final int OK_CODE = HttpStatus.SUCCESS;
    private static final String OK_MSG = "操作成功";

    /** 失败 */
    private static final int FAIL_CODE = HttpStatus.ERROR;
    private static final String FAIL_MSG = "操作失败";

    //状态
    private Integer code;
    //消息
    private String msg;
    //数据
    private List<T> data;
    //总记录数
    private Long total;
    //总页数
    @JsonIgnore
    private Long pages;
    //当前页
    @JsonIgnore
    private Long current;
    //每页条数
    @JsonIgnore
    private Long size;

    /**
     * 有参构造
     *
     * @param code 状态
     * @param msg 消息
     * @param page 分页
     */
    private PageResult(int code,String msg,IPage<T> page){
        this.code=code;
        this.msg=msg;
        if (page!=null) {
            this.data=page.getRecords();
            this.total=page.getTotal();
            this.pages=page.getPages();
            this.current=page.getCurrent();
            this.size=page.getSize();
        }
    }

    /**
     * 静态构造
     *
     * @param code 状态
     * @param msg 消息
     * @param page 分页
     * @param <T> 类型
     * @return 分页数据
     */
    private static <T> PageResult<T> pageResult(int code,String msg,IPage<T> page){
        return new PageResult<T>(code,msg,page);
    }

    //********************************成功***************************************************

    public static <T> PageResult<T> ok(IPage<T> page) {
        return ok(page, OK_CODE,OK_MSG);
    }
    public static <T> PageResult<T> ok(IPage<T> page,String msg) {
        return ok(page, OK_CODE,msg);
    }
    public static <T> PageResult<T> ok(IPage<T> page,int code) {
        return ok(page,code,OK_MSG);
    }
    public static <T> PageResult<T> ok(IPage<T> page,int code,String msg) {
        return pageResult(code,msg,page);
    }

    //********************************失败***************************************************

    public static <T> PageResult<T> fail() {
        return fail(FAIL_MSG);
    }
    public static <T> PageResult<T> fail(String msg) {
        return fail(FAIL_CODE, msg);
    }
    public static <T> PageResult<T> fail(int code,String msg) {
        return pageResult(code, msg,null);
    }
}
